const gotop = require("../common/top.js")
const qiniu = require("../../utils/qiniuCdn.js");
const share = require('../../utils/share.js')


Page({
    data: {
        mark: [{
            iconPath: "/assets/icon/map-marker.png",
            id: 0,
            latitude: 30.572269,
            longitude: 104.066541,
            width: 25,
            height: 25
        }],
        showCode: false
    },

    onLoad: function(options) {
        share(options)
        this.setData(options)
        this.setData({
            member_id: this.data.member_id ? this.data.member_id : '',
            mmid: wx.getStorageSync('mid'),
            user: wx.getStorageSync('user')
        })
        gotop.init()
        
        wx.getSystemInfo({
            success: res => {
                this.setData({
                    screenWidth: res.screenWidth
                })
                // console.log(that.data.screenWidth)
            }
        })
        getApp().http.get('city/member/qn-token').then(res => {
            this.setData({
                token: res.data
            })
        }).catch(err => {
            getApp().wxToast.error(err.message);
        })
    },
    onShow() {
        let timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        this.setData({
            timestamp
        })
        this.loadData()
        this.loadInfo()
    },

    onHide() {
        if (this.data.from == 1) {
            getApp().http.post('city/tiny-station/save-customer-trail', {
                data: {
                    time: this.data.timestamp,
                    station_member_id: this.data.member_id ? this.data.member_id : wx.getStorageSync('mid'),
                    action_type: 2,
                    action_id: this.data.item.article.id
                }
            })
        }
    },
    onUnload() {
        if (this.data.from == 1) {
            getApp().http.post('city/tiny-station/save-customer-trail', {
                data: {
                    time: this.data.timestamp,
                    station_member_id: this.data.member_id ? this.data.member_id : wx.getStorageSync('mid'),
                    action_type: 2,
                    action_id: this.data.item.article.id
                }
            })
        }

    },
    loadData() {
        // console.log(wx.getStorageSync('mid'), 'mid')
        wx.showLoading({
            title: '加载中...',
        })
        getApp().http.get("city/msg/msg-detail-v2", {
            data: {
                id: this.data.id,
                member_id: this.data.member_id ? this.data.member_id : '',
                from: this.data.from ? this.data.from : ''
            }
        }).then(res => {
            wx.setNavigationBarTitle({
                title: res.data.article.content
            })
            res.data.article.content = res.data.article.content.trim()
            this.mid = wx.getStorageSync("mid")
            this.setData({
                isMine: res.data.article.member_id == this.mid,
                // isLike: res.data.cityGroupMsgLikes.find(o => o.member_id == this.mid),
            })
            // wx.hideLoading()
            res.data.article.scan_num = +res.data.article.scan_num + 1
            res.data.articleInfo.forEach(o => {
                if (o.images) {
                    o.images = o.images.split(",").filter(o => {
                        return o.trim() && o.trim() != ","
                    })
                    o.type = 3
                } else if (o.address) {
                    o.mark = [{
                        iconPath: "/assets/icon/map-marker.png",
                        id: 0,
                        latitude: parseFloat(o.lat),
                        longitude: parseFloat(o.lng),
                        width: 25,
                        height: 25
                    }]
                    o.type = 4
                } else if (o.content) {
                    o.type = 2
                } else {
                    o.type = 1
                }
            })

            this.setData({
                item: res.data,
                selfFlag: res.data.selfFlag,
                // self_article_id: res.data.lianlin_id,
                del_one_myArticle: res.data.id
            })
        })
    },
    toStation() {
        getApp().station_id = this.data.info.member.member_id
        wx.switchTab({
            url: '/pages/microStation/index?id=' + this.data.info.member.member_id,
        })
    },
    openMap(evt) {
        const {
            map
        } = evt.currentTarget.dataset
        wx.openLocation({
            latitude: parseFloat(map.lat),
            longitude: parseFloat(map.lng),
            address: map.address
        })
    },
    onShareAppMessage() {
        let member_id = wx.getStorageSync('mid')
        console.log(this.data.from)

        if (this.data.from == 1) {
            return {
                title: this.data.item.article.content,
                path: '/pages/find/msg-detail?id=' + this.data.item.article.id + '&member_id=' + member_id + '&from=1' + '&pmid=' + wx.getStorageSync('mid'),
                success: res => {
                    // console.log('succsss111')
                    getApp().http.get("city/msg/share-article", {
                        data: {
                            id: this.data.item.article.id
                        },
                        showMsg: false
                    })
                }
            }
        } else {
            console.log('/pages/find/msg-detail?id=' + this.data.item.article.id + '&member_id=' + member_id, '222')
            return {
                title: this.data.item.article.content,
                path: '/pages/find/msg-detail?id=' + this.data.item.article.id + '&member_id=' + member_id + '&pmid=' + wx.getStorageSync('mid'),
                success: res => {
                    // console.log('succsss')
                    getApp().http.get("city/msg/share-article", {
                        data: {
                            id: this.data.item.article.id
                        },
                        showMsg: false
                    })
                }
            }
        }
    },
    onPageScroll: gotop.onPageScroll,
    showComment(evt) {
        this.setData({
            isComment: 1
        })
    },
    hideComment() {
        this.setData({
            isComment: 0
        })
    },
    submit2(evt) {
        this.submitComment({
            detail: {
                value: {
                    id: this.data.item.article.id,
                    content: evt.detail.value,
                }
            }
        })
    },
    submitComment(e) {
        wx.showLoading({
            title: '加载中...',
        })
        getApp().http.post("city/group/comment", {
            data: e.detail.value
        }).then(res => {
            wx.hideLoading()
            this.loadData()
        }).catch(err => {
            wx.hideLoading()
        })
        if (this.data.from == 1) {
            getApp().http.post('city/tiny-station/save-customer-trail', {
                data: {
                    time: this.data.timestamp,
                    station_member_id: this.data.member_id ? this.data.member_id : wx.getStorageSync('mid'),
                    action_type: 4,
                    action_id: this.data.item.article.lianlin_id,
                    action_content: e.detail.value
                }
            })
        }

    },
    // like() {
    //     getApp().http.get("city/group/like", {
    //         data: {
    //             id: this.data.item.id
    //         }
    //     }).then(res => {
    //         const arr = this.data.item.cityGroupMsgLikes
    //         res.data == 1 ? arr.pop() : arr.push(res.data)
    //         this.setData({
    //             isLike: res.data == 1 ? 0 : 1,
    //             "item.cityGroupMsgLikes": arr
    //         })
    //     })
    // },
    back() {
        getCurrentPages().length > 1 ? wx.navigateBack() : wx.reLaunch({
            url: '/pages/find/index'
        })
    },
    ds(e) {
        const {
            id,
            index,
            name,
            img,
            gid
        } = e.currentTarget.dataset
        getApp().selectedMsg = {
            id,
            index,
            name,
            img,
            gid
        }
        wx.navigateTo({
            url: '/pages/find/ds',
        })
    },

    pre(e) {
        const urls = []
        this.data.item.cityGroupMsgInfo.filter(o => o.images).forEach(o => {
            urls.push(...o.images)
        })
        wx.previewImage({
            urls,
            current: e.currentTarget.dataset.src
        })
    },

    showMenu() {
        this.setData({
            isMenu: 1
        })
    },
    hideMenu() {
        this.setData({
            isMenu: 0
        })
    },

    // drop() {
    //     wx.showModal({
    //         title: '提示',
    //         content: '是否删除该动态？',
    //         success: res => {
    //             if (res.confirm) {
    //                 wx.showLoading({
    //                     title: '加载中...',
    //                 })
    //                 getApp().http.get("city/group/delete-msg", {
    //                     data: {
    //                         gid: this.data.item.group_id,
    //                         id: this.data.item.id
    //                     }
    //                 }).then(res => {
    //                     wx.showToast({
    //                         title: '删除成功',
    //                     })
    //                     if (getCurrentPages().length > 1) {
    //                         getApp().getPrevPage().route == "pages/find/index" && getApp().getPrevPage().drop(this.data.item.id)
    //                         wx.navigateBack({

    //                         })
    //                     } else {
    //                         wx.reLaunch({
    //                             url: '/pages/find/index',
    //                         })
    //                     }
    //                 })
    //             }
    //         }
    //     })
    // },
    bigCode(evt) {

        const {
            index
        } = evt.currentTarget.dataset
        const {
            wx_code
        } = this.data
        // console.log(index, wx_code, 'imgggggg')

        wx.previewImage({
            current: wx_code[0],
            urls: wx_code,
        })

    },
    loadInfo() {
        wx.showLoading({
            title: '加载中...',
        })
        getApp().http.get('city/msg/article-bottom-info', {
            data: {
                aid: this.data.id,
                page: 0,
                member_id: this.data.member_id ? this.data.member_id : '',
                from: this.data.from ? this.data.from : ''
            }
        }).then(res => {
            var article = res.data.article.articleData.slice(0, 2)
            for (var i = 0; i < article.length; i++) {
                article[i].pic = article[i].msg_content.find(o => {
                    return !!o.images
                })
            }
            var goods = res.data.goods.goodsData.slice(0, 4)
            var wx_code = []
            if (res.data.member) {
                wx_code[0] = res.data.member.wx_qr
            }
            this.setData({
                info: res.data,
                article,
                goods,
                wx_code
            })
            wx.hideLoading()
        })
    },
    // addPhone(e) {
    //     var mobile = e.detail.value
    //     this.setData({
    //         mobile: e.detail.value
    //     })
    //     if (!mobile) {
    //         return
    //     }
    //     if (!mobile.match(/^1[3|4|5|7|8|9][0-9]\d{4,8}$/)) {
    //         wx.showToast({
    //             title: '请输入正确手机号码！',
    //             icon: 'none'
    //         })
    //         this.setData({
    //             mobile: ''
    //         })
    //         return
    //     }
    //     getApp().http.post('city/tiny-station/change-member-card', {
    //         data: {
    //             phone: mobile
    //         }
    //     }).then(res => {

    //     })
    // },

    // 打电话
    call() {
        wx.makePhoneCall({
            phoneNumber: this.data.info.member.phone,
        })
    },


    // 上传二维码
    // chooseAvatar() {
    //     wx.chooseImage({
    //         count: 1,
    //         success: res => {
    //             this.setData({
    //                 "info.member.wx_qr": res.tempFilePaths[0]
    //             })
    //             qiniu.upload(res.tempFilePaths[0], this.data.token).then(keys => {
    //                 console.log(keys, 'keys')
    //                 wx.showLoading({
    //                     title: '上传中...',
    //                 })
    //                 return getApp().http.post("city/tiny-station/change-member-card", {
    //                     data: {
    //                         wx_qr: 'https://img.zhxcxmall.com/' + keys[0]
    //                     },
    //                 }).then(res => {
    //                     console.log('88888')
    //                     wx.hideLoading()
    //                 })
    //             })
    //         }
    //     })
    // },
    bindMyarticle() {
        let c = this.data.from ? this.data.from : ''
        getApp().http.post('city/msg/become-my-msg-v2?id=' + this.data.id + '&from=' + c).then(r => {
            this.setData({
                del_id: r.data
            })
            // this.loadData()
            wx.showLoading({
                title: '加载中...',
            })
            getApp().http.get('city/msg/article-bottom-info', {
                data: {
                    aid: this.data.id,
                    page: 0,
                    member_id: '',
                    from: this.data.from ? this.data.from : ''
                }
            }).then(res => {
                getApp().station_id = ''
                var article = res.data.article.articleData.slice(0, 2)
                for (var i = 0; i < article.length; i++) {
                    article[i].pic = article[i].msg_content.find(o => {
                        return !!o.images
                    })
                    console.log('123456')
                }
                var goods = res.data.goods.goodsData.slice(0, 4)
                var wx_code = []
                wx_code[0] = res.data.member.wx_qr
                this.setData({
                    info: res.data,
                    article,
                    goods,
                    wx_code,
                    selfFlag: true,
                    member_id:''
                })
                wx.hideLoading()
            })
            this.setData({
                edit_id: r.data
            })
            // this.showMenu()
        })
    },
    // 从我的微站中移除
    delArticle() {

        wx.showModal({
            title: '提示',
            content: '您确定将【' + this.data.item.article.content + '】这篇文章，从您的微站中删除？',
            success: r => {
                if (r.confirm) {
                    getApp().http.get('city/tiny-station/del-my-article', {
                        data: {
                            lianlin_id: this.data.del_one_myArticle || this.data.del_id
                        }
                    }).then(res => {
                        wx.showToast({
                            title: '删除成功',
                            icon: 'none'
                        })
                        setTimeout(() => {
                            wx.navigateBack({

                            })
                        }, 1000)
                    })

                } else if (r.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },

    getCode() {
        this.setData({
            showCode: true
        })
        const ps = getCurrentPages()
        const path = ps[ps.length - 1].route
        const aid = this.data.id ? this.data.id : ''
        const member_id = wx.getStorageSync('mid')
        const flag = this.data.from ? this.data.from : ''
        getApp().http.post('city/msg/create-qr', {
            data: {
                path: path + '?id=' + aid + '&member_id=' + member_id + '&from=' + flag
            }
        }).then(res => {
            this.setData({
                path: res.data
            })
        })
        setTimeout(() => {
            this.saveImageToPhotosAlbum()
        }, 1000)
    },
    closeCode() {
        this.setData({
            showCode: false
        })
    },

    //定义的保存图片方法
    saveImageToPhotosAlbum: function() {
        wx.showLoading()

        function download(url) {
            return new Promise(resolve => {
                wx.downloadFile({
                    url: url,
                    success: res => {
                        resolve(res.tempFilePath);
                    }
                })
            })
        }
        var unit = this.data.screenWidth / 375

        var context = wx.createCanvasContext('share')
        context.setFillStyle('#fff')
        context.fillRect(0, 0, unit * 300, unit * 430)
        const Aimg = this.data.item.articleInfo.map(o => o.images)
        const Bimg = Aimg.filter(o => {
            return o && o.length > 0;
        }).map(o => o[0])

        // 大图
        download(Bimg[0] || 'https://pimg.ec51.com/no-image.png').then(r => {
            context.drawImage(r, unit * 10, unit * 10, unit * 280, unit * 230);
            return download(wx.getStorageSync('user').avatarUrl)
        }).then(r => {
            // 用户名
            var name = wx.getStorageSync('user').nickName
            context.setFontSize(11)
            context.setFillStyle("#333")
            context.fillText(name, unit * 50, unit * 260)
            // context.arc(unit*35, unit*275, unit*25, 0, Math.PI * 2, false);
            // context.clip();//画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
            // context.stroke()
            context.drawImage(r, unit * 15, unit * 250, unit * 30, unit * 30)
        }).then(r => {
            // 时间
            var time = new Date()
            var year = time.getFullYear()
            var mouth = time.getMonth() + 1
            var date = time.getDate()
            var time2 = year + '-' + mouth + '-' + date
            console.log(time2, 'time')
            context.setFontSize(10)
            context.setFillStyle("#999")
            context.fillText(time2, unit * 50, unit * 280)
        }).then(r => {
            var now = '正在' + wx.getStorageSync('store') + '上读这篇文章'
            context.setFontSize(10)
            context.setFillStyle("#999")
            context.fillText(now, unit * 110, unit * 280)
        }).then(r => {
            // 商品名称
            var aname = this.data.item.article.content
            // context.setFontSize(18)
            // context.setFillStyle("#333")
            // context.fillText(aname, unit * 15, unit * 315, unit * 300);

            var chr = aname.split(""); //这个方法是将一个字符串分割成字符串数组
            var temp = "";
            var row = [];
            context.setFontSize(18)
            context.setFillStyle("#333")
            for (var a = 0; a < chr.length; a++) {
                if (context.measureText(temp).width < 250) {
                    temp += chr[a];
                } else {
                    a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
                    row.push(temp);
                    temp = "";
                }
            }
            row.push(temp);

            //如果数组长度大于2 则截取前两个
            if (row.length > 2) {
                var rowCut = row.slice(0, 2);
                var rowPart = rowCut[1];
                var test = "";
                var empty = [];
                for (var a = 0; a < rowPart.length; a++) {
                    if (context.measureText(test).width < 220) {
                        test += rowPart[a];
                    } else {
                        break;
                    }
                }
                empty.push(test);
                var group = empty[0] + "..." //这里只显示两行，超出的用...表示
                rowCut.splice(1, 1, group);
                row = rowCut;
            }
            for (var b = 0; b < row.length; b++) {
                context.fillText(row[b], 10, 315 + b * 30, 300);
            }

            // var chr = aname.split(""); //这个方法是将一个字符串分割成字符串数组
            // var temp = "";
            // var row = [];
            // for (var a = 0; a < chr.length; a++) {
            //   if (context.measureText(temp).width < 180) {
            //     temp += chr[a];
            //   } else {
            //     a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
            //     row.push(temp);
            //     temp = "";
            //   }
            // }
            // row.push(temp);
            // console.log(row, 'row')
            // context.fillText(row[0] + "...", unit * 15, unit * 310, 350);
            console.log(this.data.path, 'path')
            return download(this.data.path)
        }).then(r => {
            // 小程序码
            var des = '长按小程序码'
            context.setFontSize(12)
            context.setFillStyle("#666")
            context.fillText(des, unit * 85, unit * 390, unit * 300);
            context.drawImage(r, unit * 15, unit * 360, unit * 60, unit * 60)
        }).then(r => {
            var join = '进入' + wx.getStorageSync('store') + '阅读全文'
            context.setFontSize(12)
            context.setFillStyle("#666")
            context.fillText(join, unit * 85, unit * 410, unit * 300);
        }).then(r => {
            context.draw(false, function() {
                wx.hideLoading();
            })
        })
    },
    save() {
        var that = this
        var unit = that.data.screenWidth / 375
        wx.showLoading({
            title: '保存中',
        })
        wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: unit * 300,
            height: unit * 500,
            destWidth: unit * 800,
            destHeight: unit * 1100,
            quality: 1,
            canvasId: 'share',
            success: function(res) {
                that.setData({
                    shareImgPath: res.tempFilePath,
                    scope: false
                })
                if (!res.tempFilePath) {
                    wx.showToast({
                        title: '请稍后重试',
                        icon: 'none'
                    })

                }
                //画板路径保存成功后，调用方法吧图片保存到用户相册
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    //保存成功失败之后，都要隐藏画板，否则影响界面显示。
                    success: (res) => {
                        setTimeout(() => {
                            wx.showToast({
                                title: '已保存到系统相册',
                                icon: 'none'
                            })
                        }, 1000)
                        setTimeout(() => {
                            that.setData({
                                showCode: false
                            })
                        }, 1500)
                        wx.hideLoading()

                    },
                    fail: (err) => {
                        console.log(err, '123456789');
                        wx.hideLoading()
                        wx.showToast({
                            title: '保存失败，请稍后再试',
                            icon: 'none'
                        })
                        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                            console.log("当初用户拒绝，再次发起授权")
                            that.setData({
                                scope: true
                            })
                        }
                    }
                })
            }
        })
    },
})